﻿using Game.Entity.Accounts;
using Game.Entity.Treasure;
using Game.Facade;
using Game.Kernel;
using Game.Utils;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Game.Card.Pay.WX
{
    public partial class Wxpay : AdminPage
    {
        public string formData = string.Empty;
        public string js = string.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
            {
                //充值配置验证
                int payId = GameRequest.GetInt("id", 0);
                if(payId <= 0)
                {
                    Response.Redirect("/Menu/Buy.aspx");
                }
                RoomCardConfig config = FacadeManage.aideTreasureFacade.GetRoomCardConfig(payId);
                if(config == null)
                {
                    Response.Redirect("/Menu/Buy.aspx");
                }
                if(config.Amount <= 0 || config.RoomCard <= 0)
                {
                    ShowInfo("充值配置参数错误");
                    return;
                }

                // 支付方法
                string orderID = PayHelper.GetOrderIDByPrefix("WapWX");
                OnLineOrder onlineOrder = new OnLineOrder();
                onlineOrder.ShareID = 81;
                onlineOrder.OrderID = orderID;

                UserTicketInfo info = userTicket;

                onlineOrder.OperUserID = info.UserID;
                onlineOrder.GameID = info.GameID;
                onlineOrder.OrderAmount = config.Amount;
                onlineOrder.IPAddress = GameRequest.GetUserIP();

                //生成订单
                Message umsg = FacadeManage.aideTreasureFacade.RequestOrderFK(onlineOrder, payId);
                if(!umsg.Success)
                {
                    ShowInfo(umsg.Content);
                    return;
                }

                //随机字符串
                string nonce_str = WeiXinHelper.GetNonce_str();
                //商品描述
                string body = "充值房卡";
                //商户订单号
                string out_trade_no = orderID;
                //交易金额（分为单位）
                int total_fee = Convert.ToInt32(config.Amount * 100);
                //终端IP
                string spbill_create_ip = Utility.UserIP;
                //回调地址
                string notify_url = "http://" + Request.Url.Authority + "/Pay/WX/WxpayNotify.aspx";
                //商品ID
                string product_id = orderID.Substring(5, orderID.Length - 5);

                SortedDictionary<string, object> dic = new SortedDictionary<string, object>();
                dic.Add("nonce_str", nonce_str);
                dic.Add("body", body);
                dic.Add("trade_type", "NATIVE");
                dic.Add("out_trade_no", out_trade_no);
                dic.Add("total_fee", total_fee);
                dic.Add("spbill_create_ip", spbill_create_ip);
                dic.Add("notify_url", notify_url);
                dic.Add("product_id", product_id);

                SortedDictionary<string, object> result = WeiXinHelper.UnifiedOrder(dic, 10);
                string code = result["return_code"].ToString();
                StringBuilder builder = new StringBuilder();
                builder.AppendLine(CreateInputHidden("return_code", code));
                builder.AppendLine(CreateInputHidden("return_msg", result["return_msg"].ToString()));
                if(code == "SUCCESS")
                {
                    builder.AppendLine(CreateInputHidden("code_url", result["code_url"].ToString()));
                    builder.AppendLine(CreateInputHidden("orderID", out_trade_no));
                    builder.AppendLine(CreateInputHidden("amount", config.Amount.ToString()));
                }

                formData = builder.ToString();

                js = "<script>window.onload = function() { document.forms[0].submit(); }</script>";
            }







            //NativePay nativePay = new NativePay();

            //string url2 = nativePay.GetPayUrl("123456789");
            //Image2.ImageUrl = "MakeQRCode.aspx?data=" + HttpUtility.UrlEncode(url2);

            ////初始化二维码生成工具
            //QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
            //qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
            //qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
            //qrCodeEncoder.QRCodeVersion = 0;
            //qrCodeEncoder.QRCodeScale = 4;

            ////将字符串生成二维码图片
            //Bitmap image = qrCodeEncoder.Encode(str, Encoding.Default);

            ////保存为PNG到内存流  
            //MemoryStream ms = new MemoryStream();
            //image.Save(ms, ImageFormat.Png);

            ////输出二维码图片
            //Response.BinaryWrite(ms.GetBuffer());
            //Response.End();
        }

        #region 公共方法

        //功能函数。将变量值不为空的参数组成字符串
        private String AppendParam(String returnStr, String paramId, String paramValue)
        {
            if(returnStr != "")
            {
                if(paramValue != "")
                {
                    returnStr += "&" + paramId + "=" + paramValue;
                }
            }
            else
            {
                if(paramValue != "")
                {
                    returnStr = paramId + "=" + paramValue;
                }
            }

            return returnStr;
        }

        //隐藏字段
        private string CreateInputHidden(string idName, string value)
        {
            return String.Format("<input type=\"hidden\" id=\"{0}\" value=\"{1}\" name=\"{0}\" />", idName, value);
        }
        #endregion
    }
}